<template>
  <el-dialog :model-value="dialogVisible" width="80%" max-width="400px" class="commodity-select-dialog"
    @close="handleClose" :close-on-click-modal="false">

    <!-- 使用插槽自定义标题 -->
    <template #header="{ titleId, titleClass }">
      <div class="dialog-header">
        <span :id="titleId" :class="titleClass">选择商品</span>
        <span v-if="subTitle" class="sub-title">{{ subTitle }}</span>
      </div>
    </template>

    <!-- 搜索栏 -->
    <el-row>
      <el-col :span="24" style="padding-left: 24px;">
        <el-form :inline="true" :model="filter" class="demo-form-inline">
          <el-form-item label="编号">
            <el-input v-model="filter.code" placeholder="商品编号" clearable />
          </el-form-item>
          <el-form-item label="名称">
            <el-input v-model="filter.subCommodityName" placeholder="商品名称" clearable />
          </el-form-item>
          <el-form-item label="规格">
            <el-input v-model="filter.standName" placeholder="商品规格" clearable />
          </el-form-item>

          <category-select v-model="filter.category" label="类别" :basic-ui-action="basicUiAction"
            @change="handleCategoryChange" />

          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>

    <!-- 操作按钮 -->
    <div style="margin-bottom: 10px; text-align: right;">
      <el-button type="primary" @click="handleBatchSelect">选择选中商品</el-button>
    </div>

    <!-- 数据列表 -->
    <el-table ref="table" v-loading="loading" :data="inventoryDataList" style="width: 100%" border
      @selection-change="handleSelectionChange" row-key="id" :row-class-name="rowClassName">
      <el-table-column type="selection" :reserve-selection="true" width="55" :selectable="isSelectable" />

      <el-table-column label="图片" align="center" width="100">
        <template #default="scope">
          <el-image style="width: 60px; height: 60px" :src="scope.row.subCommodity.imgs"
            :preview-src-list="[scope.row.subCommodity.imgs]" fit="cover" v-if="scope.row.subCommodity.imgs">
            <template #error>
              <div class="image-slot">
                <el-icon>
                  <Picture />
                </el-icon>
              </div>
            </template>
          </el-image>
          <div v-else class="empty-image">
            <el-icon>
              <Picture />
            </el-icon>
          </div>
        </template>
      </el-table-column>

      <el-table-column v-if="!isMetalMerchantOrg" prop="subCommodity.code" label="编号" align="center" width="120" />

      <el-table-column prop="subCommodity.name" label="商品名称" align="center" show-overflow-tooltip />

      <el-table-column v-if="!isMetalMerchantOrg" label="类别" align="center" width="100">
        <template #default="scope">
          {{ scope.row.subCommodity.category?.name || '-' }}
        </template>
      </el-table-column>

      <el-table-column v-if="!isMetalMerchantOrg" prop="subCommodity.standard" label="规格" align="center" width="100" />


      <el-table-column v-if="isMetalMerchantOrg" label="回购价" align="center" width="100">
        <template #default="scope">
          {{ formatMetalPrice(scope.row.subCommodity, scope.row.subCommodity.purchasePrice) }}
        </template>
      </el-table-column>

      <el-table-column v-if="isMetalMerchantOrg" label="销售价" align="center" width="100">
        <template #default="scope">
          {{ formatMetalPrice(scope.row.subCommodity, scope.row.subCommodity.retailPrice) }}
        </template>
      </el-table-column>

      <el-table-column label="单位" align="center" width="80">
        <template #default="scope">
          {{ scope.row.subCommodity.unit?.name || '-' }}
        </template>
      </el-table-column>

      <el-table-column prop="availableCount" label="可用库存" align="right" width="100">
        <template #default="scope">
          {{ formatCount(scope.row.availableCount) }}
        </template>
      </el-table-column>

      <el-table-column prop="totalInventoryCount" label="当前库存" align="right" width="100">
        <template #default="scope">
          {{ formatCount(scope.row.totalInventoryCount) }}
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="100">
        <template #default="scope">
          <el-button size="small" type="primary" @click="handleSelect(scope.row)" :disabled="!isSelectable(scope.row)">
            选择</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div style="margin-top: 20px; text-align: right">
      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="fetchInventoryData" />
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { ElMessage } from 'element-plus'
import { Picture } from '@element-plus/icons-vue'
import { InventoryUiAction } from '../../public/engine/uiAction/inventoryUiAction'
import { Definition } from '../../public/engine/common/definition'
import { DataPage } from '../../public/network/communicationConverter'
import { Util } from '../../public/utils/util'
import { SubCommodityInventorySumFilter } from '../../public/engine/commodity/subCommodityInventorySum'
import { Engine } from '../../public/engine/engine'
import CategorySelect from '../../public/views/componentsWeb/CategorySelect.vue'
import { MetalUtil } from '../../public/utils/metalUtil'
import { format } from 'echarts'

export default {
  name: 'subcommoditySelectDialog',
  components: {
    Picture,
    CategorySelect
  },
  props: {
    basicUiAction: {
      type: Object,
      required: true
    }
  },
  emits: ['select', 'close'],
  data() {
    return {
      dialogVisible: false,
      loading: false,
      inventoryDataList: [],
      total: 0,
      selectedItems: [],
      selectedCommodities: [], // 已选择的商品列表 上级UI 传入，类型 CommodityBatch
      excludeCommodities: [],
      filter: new SubCommodityInventorySumFilter(),
      queryParams: {
        pageNum: 1,
        pageSize: Definition.gDefualPageSize
      },
      inventoryUiAction: new InventoryUiAction(),
      subTitle: null,
      metalUtil: MetalUtil.getInstance(),
      metalPriceData: null,  // 金属价格
    }
  },

  computed: {
    // 获取已选择的商品列表
    isMetalMerchantOrg() {
      return Engine.profile.org.isPreciousMetalOrg;
    }
  },

  methods: {
    // 打开弹窗方法，参考 customerBasicInfoDialog 中的 open 方法
    open(selectedCommodityList, { excludeCommodities = [], warehouse = null } = {}) {
      this.dialogVisible = true
      this.filter.clear();
      this.filter.wareHouse = warehouse
      if (warehouse) {
        this.subTitle = warehouse.name
      }
      else {
        this.subTitle = null;
      }
      this.selectedCommodities = selectedCommodityList || []
      this.excludeCommodities = excludeCommodities || []
      this.queryParams.pageNum = 1
      // 清空 selection
      this.$nextTick(() => {
        // console.log('clearSelection')
        this.$refs.table?.clearSelection();
      });
      this.fetchInventoryData();

      // 订阅贵金属价格更新
      if (this.isMetalMerchantOrg) {
        this.metalUtil.subscribe(this.getMetalPriceCallback);
      }
    },

    // 判断商品是否可选择
    isSelectable(row, index) {
      // 如果没有排除商品列表，则所有商品都可选择
      if (!this.excludeCommodities || this.excludeCommodities.length === 0) {
        return true;
      }

      // 检查当前商品是否在排除列表中
      return !this.excludeCommodities.some(
        item => item.commodity.id === row.subCommodity.id
      );
    },

    async fetchInventoryData() {
      try {
        this.loading = true

        const res = await this.inventoryUiAction.getSubCommodityInventorySumData({
          pageInfo: new DataPage(this.queryParams.pageNum, 0, this.queryParams.pageSize),
          filter: this.filter.toJson()
        })

        if (res && res.data && res.data.dataList) {
          this.inventoryDataList = res.data.dataList
          this.total = res.data.pageInfo.total

          // 标记已选择的商品

          this.$nextTick(() => {
            //  this.markSelectedItems()
          })

        } else if (res.resErr) {
          ElMessage.error('获取库存数据失败')
        }
      } catch (error) {
        console.error('获取库存数据失败:', error)
        ElMessage.error('获取库存数据失败')
      } finally {
        this.loading = false
      }
    },

    // 标记已选择的商品
    markSelectedItems() {
      // console.log('this.selectedCommodities', this.selectedCommodities)
      if (this.selectedCommodities && this.selectedCommodities.length > 0) {
        this.inventoryDataList.forEach(row => {
          const isSelected = this.selectedCommodities.some(
            item => item.commodity.id === row.subCommodity.id
          )
          if (isSelected) {
            // console.log("markSelectedItems:",row.subCommodity.name)
            this.$refs.table?.toggleRowSelection(row, true)
          }
        })
      }
    },

    handleSearch() {
      this.queryParams.pageNum = 1
      this.fetchInventoryData()
    },

    resetSearch() {
      this.filter.clear()
      this.queryParams.pageNum = 1
      this.fetchInventoryData()
    },

    formatCount(value) {
      return Util.getCountString(value)
    },

    formatMetalPrice(subCommodity, price) {
      if (Util.isEmpty(subCommodity.metalCode)) {
        return '--';
      }
      return Util.getFundString(price?.value, { currencyCharector: false })
    },

    handleCategoryChange(val) {
      this.filter.category = val
    },

    // 处理选择变化
    handleSelectionChange(selection) {
      //console.log('handleSelectionChange:', selection)
      this.selectedItems = selection
    },

    // 批量选择商品
    handleBatchSelect() {
      if (this.selectedItems.length === 0) {
        ElMessage.warning('请选择至少一个商品')
        return
      }

      this.$emit('select', this.selectedItems)
      this.handleClose()
    },

    // 单个选择商品
    handleSelect(item) {
      this.$emit('select', [item])
      this.handleClose()
    },

    // 关闭弹窗
    handleClose() {
      this.dialogVisible = false;
      this.metalUtil.unsubscribe(this.getMetalPriceCallback)
      this.$emit('close')
    },

    rowClassName({ row }) {
      //  console.log('rowClassName', row)
      try {
        if (
          this.selectedCommodities.some(
            item => item.commodity.id === row.subCommodity.id
          )
        ) {
          //  console.log('already-selected-row')
          return 'already-selected-row';
        }
      } catch (e) {
        console.log("rowClassName error:", e);
      }
      return '';
    },

    // 贵金属价格
    // 贵金属价格
    getMetalPriceCallback(data) {
      //console.log('getMetalPriceCallback', data)
      this.metalPriceData = data;

      // The data is nested in an array, so we need to access the first element
      const metalPrices = this.metalPriceData[0];

      // Update the inventory data list with matching metal prices
      for (let i = 0; i < this.inventoryDataList.length; i++) {
        const commodity = this.inventoryDataList[i].subCommodity;

        // Find matching metal price data based on metalCode
        if (commodity.metalCode) {
          const matchingPrice = metalPrices.find(price => price.CODE === commodity.metalCode);

          if (matchingPrice) {
            // Use Vue.set or direct assignment to ensure reactivity
            // this.$set(commodity, 'metalPriceInfo', matchingPrice);
            // this.$set(commodity, 'metalPrice', matchingPrice.ASK);
            commodity.purchasePrice = Util.jsonToCsFundDouble(matchingPrice.BID, 0);
            commodity.retailPrice = Util.jsonToCsFundDouble(matchingPrice.ASK, 0);
          }
        }
      }
    }
  }
}
</script>

<style scoped>
/* 添加标题样式 */
.dialog-header {
  display: flex;
  align-items: baseline;
}

.dialog-header span:first-child {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.sub-title {
  margin-left: 12px;
  font-size: 13px;
  color: #909399;
  font-weight: normal;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
}

.empty-image {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 60px;
  height: 60px;
  background: #f5f7fa;
  color: #909399;
}
</style>

<style>
.commodity-select-dialog {
  max-width: 1000px !important;
}

/* 推荐：高亮整行 */
/*
.already-selected-row {
  background: #ffae00 !important;
}
*/
/* 或只高亮 selection 列 */
.already-selected-row td.el-table__cell:first-child {
  background: #d9f0ff !important;
}
</style>